<?php
class SGObjetoConexaoMDB2 implements SGObjetoConexao {
	
	protected $conn;
	
	public function __construct(){
		$dsn = array(
			'username' => 'root',
			'password' => '',
			'database' => 'base',
			'phptype' => 'mysql',
			'hostspec' => 'localhost',
		);
		
		$options = array(
		    'debug'       => 2,
		    'portability' => MDB2_PORTABILITY_ALL,
		    'field_case'  => CASE_UPPER
		);
		
		$this->conn =& MDB2::connect($dsn, $options);
		
		if (PEAR::isError($this->conn))
			$this->handleConectionNotFound('conexao.erro.not.connected');
		
		$this->conn->setFetchMode(MDB2_FETCHMODE_OBJECT);
		$this->conn->query("SET CHARACTER SET 'utf8'");
		$this->conn->loadModule('Manager');
	}

	public function execute($sql){
		if($this->isValid())
			$this->handleConectionNotFound();
		
		$sth = $this->conn->prepare($sql);
		
		if (PEAR::isError($sth)) $this->handleInvalidSQL("conexao.erro.valores_incorretos");
		
		$res = $sth->execute();
		
		$this->free($sth);
		
		if(PEAR::isError($res)) $this->handleInvalidSQL("conexao.erro.valores_incorretos");
		
		return $res;
	}

	public function queryOne($sql){
		if($this->isValid())
			$this->handleConectionNotFound();
		
		$total = $this->conn->queryOne($sql);
		if (PEAR::isError($total)) throw new handleInvalidSQL("conexao.erro.valores_incorretos");
		return $total;
	}

	public function nextid($nomeTabela){
		if($this->isValid())
			$this->handleConectionNotFound();
		
		return $this->conn->nextid($nomeTabela);
	}

	public function isValid(){
		return is_resource($this->conn);
	}
	
	public function fetchRow($resource){
		return $resource->fetchRow();
	}
	
	public function numRows($resource){
		return $resource->numRows();
	}
	
	public function free($resource){
		$resource->free();
	}
	
	public function beginTransaction(){
		if(!$this->conn->supports('transactions'))
			$this->handleConectionNotFound('conexao.erro.transacao.nao.suportada');
		
		$this->conn->beginTransaction();
	}
	
	public function commit(){
		if(!$this->conn->inTransaction())
			$this->handleConectionNotFound('conexao.erro.transacao.nao.iniciada');
		
		$this->conn->commit();
	}
	
	public function rollback(){
		if(!$this->conn->inTransaction())
			$this->handleConectionNotFound('conexao.erro.transacao.nao.iniciada');
		
		$this->conn->rollback();
	}
	
	private function handleInvalidSQL($msg=false){
		throw new SGObjetoInvalidSQLException($msg ? $msg : "conexao.erro.geracao.sql.insert");
	}
	
	private function handleConectionNotFound($msg=false){
		throw new SGObjetoConectionNotFoundException($msg ? $msg : "conexao.erro.invalida");
	}
	
}
?>